import React from 'react';
import {connect} from 'react-redux'
import {messages} from "share/common";
import {Button, Col, Icon, message, Modal, Popover, Row} from "antd"
import Skeleton from 'components/skeleton'
import SlideFrame from 'components/slide-frame'
import Condition from 'components/condition'
import SubsidyContent from "containers/expense-report/subsidy-content";
import subsidyService from "containers/expense-report/template/subsidy-service";
import 'styles/expense-report/components/subsidy-slide-frame.scss'

const { If } = Condition;

class ExpenseDetailAlert extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      buttonLoading: false,
      subsidyInfo: {},
      userOption: [],
      slideFrameShow: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.visible || nextProps.visible === this.props.visible)
      return;
    this.setState({ slideFrameShow: nextProps.visible }, this.getSubsidyInfo())
  }

  //获取差补详情
  getSubsidyInfo = () => {
    const { expenseReportOID, newOtherSubsidy } = this.props.expenseInfo;
    this.setState({ loading: true });
    Promise.all([
      subsidyService.getDataList(expenseReportOID),
      newOtherSubsidy && subsidyService.getUserList(expenseReportOID)
    ]).then(res => {
      this.setState({
        subsidyInfo: res[0].data || {},
        userOption: newOtherSubsidy ? res[1].data.rows : [],
      }, () => { //子组件<SubsidyContent/>接收到subsidyInfo和userOption后再将loading置为false
        this.setState({ loading: false })
      })
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('expense-parent-report.key152')/*系统异常*/);
    })
  };

  //自动计算行程
  handleCalculate = (checkFlag = true) => {
    const { expenseInfo } = this.props;
    let params = {
      expenseReportOID: expenseInfo.expenseReportOID,
      checkFlag: checkFlag
    };
    // 自动计算参数 checkFlag为true时仅查验数据不覆盖为false时才覆盖
    this.setState({ loading: true, buttonLoading: true });
    subsidyService.getAutoSubsidy(params).then(res => {
      if (res.data && (res.data.expenseReportSubsidyViewList || []).length) {
        const sourceSubsidyInfo = this.state.subsidyInfo;
        let sourceSubsidyList = sourceSubsidyInfo.expenseReportSubsidyViewList || [];
        if (checkFlag) { // 为true是后台不覆盖
          if ((sourceSubsidyList.length > 0 ||
              (sourceSubsidyList[0].expenseReportSubsidyDTOS || []).length)
          ) {
            //当前需要确认处理已有行程记录
            Modal.confirm({
              title: messages('expense-parent-report.key181')/*将会覆盖已填写的行程*/,
              iconType: 'info-circle',
              onOk: () => this.handleCalculate(false),
              onCancel: () => {
                this.setState({loading: false, buttonLoading: false})
              }
            });
          } else {
            this.handleCalculate(false)
          }
          return !1;
        }
        let subsidyInfo = res.data;
        subsidyInfo.expenseReportSubsidyViewList.map(item => {
          item.expenseReportSubsidyDTOS.map(subItem => {
            subItem.edit = true;
            if (res.data.subsidySelection) {
              let expenseTypeOIDs = [];
              subItem.expenseTypes && subItem.expenseTypes.map(expenseItem => {
                expenseTypeOIDs.push(expenseItem.expenseTypeOID)
              });
              subItem.expenseTypeOIDs = expenseTypeOIDs;
            }
          })
        });
        this.setState({
          subsidyInfo
        }, () => { //子组件<SubsidyContent/>接收到subsidyInfo和userOption后再将loading置为false
          this.setState({ loading: false, buttonLoading: false })
        })
      } else {
        Modal.error({
          title: messages('expense-parent-report.key182')/*无可用的行程或订单*/,
          content: messages('expense-parent-report.key183')/*请返回报销单页面填写*/,
          onOk: () => this.setState({ loading: false, buttonLoading: false })
        })
      }
    }).catch(e => {
      this.setState({ loading: false, buttonLoading: false });
      message.error(e.response.data.message || messages('expense-parent-report.key152')/*系统异常*/);
    })
  };

  handleClose = (isRefresh) => {
    this.setState({
      slideFrameShow: false,
      subsidyInfo: {}
    }, () => this.props.afterClose(isRefresh))
  };

  //SlideFrame Title
  renderFrameTitle = () => {
    const { buttonLoading, subsidyInfo } = this.state;
    return (
      <Row className="subsidy-frame-title">
        <Col span={6}>
          {messages('expense-parent-report.key40'/*补贴计算*/)}
          <If value={subsidyInfo.subsidyTips}>
            <Popover placement="bottomLeft" content={subsidyInfo.subsidyTips} overlayStyle={{maxWidth: 500}}>
              <Icon type="info-circle" className="subsidy-info-icon"/>
            </Popover>
          </If>
        </Col>
        <If value={subsidyInfo.isAutoCalculateEnabled}>
          <Col span={18} className="auto-calculate-subsidy"> {messages('expense-parent-report.key184')/*费用填写完整后再点击[自动计算行程]*/}
            <Button type="primary"
                    size="small"
                    className="button-calculate"
                    loading={buttonLoading}
                    onClick={() => this.handleCalculate()}>{messages('expense-parent-report.key185')/*自动计算行程*/}</Button>
          </Col>
        </If>
      </Row>
    )
  };

  renderFrameContent = () => {
    const { loading } = this.state;
    return (
      <div>
        <Skeleton loading={loading}>
          {SubsidyContent}
        </Skeleton>
      </div>
    )
  };

  render() {
    const { expenseInfo } = this.props;
    const { loading, subsidyInfo, userOption, slideFrameShow } = this.state;
    return (
      <div className="subsidy-slide-frame">
        <SlideFrame
          show={slideFrameShow}
          title={this.renderFrameTitle()}
          content={SubsidyContent}
          hasMask={false}
          width="880px"
          params={{
            loading,
            subsidyInfo,
            userOption,
            subsidyFrame: slideFrameShow,
            expenseReportOID: expenseInfo.expenseReportOID,
            expenseInfo
          }}
          onClose={this.handleClose}
          afterClose={this.handleClose}
          hasFooter={false}
        />
      </div>
    )
  }
}

ExpenseDetailAlert.propsType = {
  visible: React.PropTypes.bool, //差补侧滑框是否显示
  expenseInfo: React.PropTypes.object, //报销单详情
  afterClose: React.PropTypes.func, //关闭差补侧滑框
};

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(ExpenseDetailAlert)
